import { Pause, Play, Volume2, VolumeX, X } from 'lucide-react'
import { useEffect, useRef, useState, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Slider } from '@/components/ui/slider'
import { cn } from '@/lib/utils'

interface AudioPlayerProps {
  base64Audio: string | null
  autoPlay?: boolean
  onPlayComplete?: () => void
  onPlayError?: (error: string) => void
  onPlayStarted?: () => void
  onClose?: () => void
}

export function AudioPlayer({
  base64Audio,
  autoPlay = true,
  onPlayComplete,
  onPlayError,
  onPlayStarted,
  onClose,
}: AudioPlayerProps) {
  const audioRef = useRef<HTMLAudioElement | null>(null)
  const [isPlaying, setIsPlaying] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)
  const [volume, setVolume] = useState(100)
  const [isMuted, setIsMuted] = useState(false)
  const callbacksRef = useRef({ onPlayComplete, onPlayError, onPlayStarted, autoPlay })

  // 更新回调 refs
  useEffect(() => {
    callbacksRef.current = { onPlayComplete, onPlayError, onPlayStarted, autoPlay }
  })

  // 初始化音频 - 只依赖 base64Audio
  useEffect(() => {
    if (!base64Audio) {
      return
    }

    console.log('[AudioPlayer] 初始化音频，Base64长度:', base64Audio.length)

    // 创建 Audio 对象
    const dataUrl = `data:audio/mp3;base64,${base64Audio}`
    const audio = new Audio(dataUrl)
    audio.volume = volume / 100

    // 事件监听
    const handleLoadedMetadata = () => {
      setDuration(audio.duration)
      console.log('[AudioPlayer] 元数据加载完成')
    }

    const handlePlay = () => {
      console.log('[AudioPlayer] 播放事件')
      setIsPlaying(true)
    }

    const handlePause = () => {
      console.log('[AudioPlayer] 暂停事件')
      setIsPlaying(false)
    }

    const handleTimeUpdate = () => {
      setCurrentTime(audio.currentTime)
    }

    const handleEnded = () => {
      console.log('[AudioPlayer] 播放结束')
      setIsPlaying(false)
      setCurrentTime(0)
      callbacksRef.current.onPlayComplete?.()
    }

    const handleError = () => {
      console.error('[AudioPlayer] 音频错误')
      setIsPlaying(false)
      callbacksRef.current.onPlayError?.('音频播放失败')
    }

    const handleCanPlayThrough = () => {
      console.log('[AudioPlayer] 音频已准备好，autoPlay=', callbacksRef.current.autoPlay)
      
      if (callbacksRef.current.autoPlay) {
        console.log('[AudioPlayer] 开始自动播放')
        audio.play()
          .then(() => {
            console.log('[AudioPlayer] 自动播放成功')
            callbacksRef.current.onPlayStarted?.()
          })
          .catch((error) => {
            console.error('[AudioPlayer] 自动播放失败:', error)
          })
      }
    }

    // 绑定事件
    audio.addEventListener('loadedmetadata', handleLoadedMetadata)
    audio.addEventListener('play', handlePlay)
    audio.addEventListener('pause', handlePause)
    audio.addEventListener('timeupdate', handleTimeUpdate)
    audio.addEventListener('ended', handleEnded)
    audio.addEventListener('error', handleError)
    audio.addEventListener('canplaythrough', handleCanPlayThrough)

    audioRef.current = audio

    // 清理函数
    return () => {
      console.log('[AudioPlayer] 清理音频')
      audio.removeEventListener('loadedmetadata', handleLoadedMetadata)
      audio.removeEventListener('play', handlePlay)
      audio.removeEventListener('pause', handlePause)
      audio.removeEventListener('timeupdate', handleTimeUpdate)
      audio.removeEventListener('ended', handleEnded)
      audio.removeEventListener('error', handleError)
      audio.removeEventListener('canplaythrough', handleCanPlayThrough)
      audio.pause()
      audioRef.current = null
    }
  }, [base64Audio, volume])

  // 播放/暂停
  const togglePlayPause = () => {
    if (!audioRef.current) {
      console.error('[AudioPlayer] togglePlayPause: audioRef.current 为空！')
      return
    }
    
    if (isPlaying) {
      console.log('[AudioPlayer] 暂停播放')
      audioRef.current.pause()
    } else {
      console.log('[AudioPlayer] 开始播放')
      audioRef.current.play().catch((error) => {
        console.error('[AudioPlayer] 播放失败:', error)
      })
    }
  }

  // 调整进度
  const handleProgressChange = (value: number[]) => {
    if (!audioRef.current) return
    const newTime = value[0]
    audioRef.current.currentTime = newTime
    setCurrentTime(newTime)
  }

  // 调整音量
  const handleVolumeChange = (value: number[]) => {
    const newVolume = value[0]
    setVolume(newVolume)
    if (audioRef.current) {
      audioRef.current.volume = newVolume / 100
    }
    if (newVolume > 0) {
      setIsMuted(false)
    }
  }

  // 静音/取消静音
  const toggleMute = () => {
    if (!audioRef.current) return

    if (isMuted) {
      audioRef.current.volume = volume / 100
      setIsMuted(false)
    } else {
      audioRef.current.volume = 0
      setIsMuted(true)
    }
  }

  // 格式化时间
  const formatTime = (seconds: number) => {
    if (isNaN(seconds)) return '0:00'
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  // 如果没有音频数据，不显示播放器
  if (!base64Audio || base64Audio.length === 0) {
    return null
  }
  
  return (
    <div className="bg-white border-t border-gray-200 px-4 py-3 shadow-lg">
      <div className="flex items-center gap-4 max-w-7xl mx-auto">
        {/* 播放/暂停按钮 */}
        <Button
          variant="ghost"
          size="icon"
          onClick={togglePlayPause}
          className="h-10 w-10"
        >
          {isPlaying ? (
            <Pause className="h-5 w-5" />
          ) : (
            <Play className="h-5 w-5" />
          )}
        </Button>

        {/* 当前时间 */}
        <span className="text-sm text-muted-foreground min-w-[45px]">
          {formatTime(currentTime)}
        </span>

        {/* 进度条 */}
        <div className="flex-1 max-w-2xl">
          <Slider
            value={[currentTime]}
            max={duration || 100}
            step={0.1}
            onValueChange={handleProgressChange}
            className="cursor-pointer"
          />
        </div>

        {/* 总时长 */}
        <span className="text-sm text-muted-foreground min-w-[45px]">
          {formatTime(duration)}
        </span>

        {/* 音量控制 */}
        <div className="flex items-center gap-2 min-w-[140px]">
          <Button
            variant="ghost"
            size="icon"
            onClick={toggleMute}
            className="h-8 w-8"
          >
            {isMuted || volume === 0 ? (
              <VolumeX className="h-4 w-4" />
            ) : (
              <Volume2 className="h-4 w-4" />
            )}
          </Button>
          <div className="w-20">
            <Slider
              value={[isMuted ? 0 : volume]}
              max={100}
              step={1}
              onValueChange={handleVolumeChange}
              className="cursor-pointer"
            />
          </div>
        </div>

        {/* 播放状态指示 */}
        <div
          className={cn(
            'text-xs px-2 py-1 rounded',
            isPlaying
              ? 'bg-green-100 text-green-700'
              : 'bg-gray-100 text-gray-500',
          )}
        >
          {isPlaying ? '播放中' : '已暂停'}
        </div>

        {/* 关闭按钮 */}
        {onClose && (
          <Button
            variant="ghost"
            size="icon"
            onClick={onClose}
            className="h-8 w-8"
            title="关闭播放器"
          >
            <X className="h-4 w-4" />
          </Button>
        )}
      </div>
    </div>
  )
}

